package com.app.aipass.fragment.my.exchangepoints.exchangepointsrecord;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppApplication;
import com.app.aipass.data.DemoRepository;
import com.app.aipass.entity.BillEntity;
import com.app.aipass.entity.ExchangeLogEntity;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * @author: woking
 * @date: 2021/6/10
 * @description：
 */
public class ExchangePointsRecordViewModel extends BaseViewModel<DemoRepository> {
    private int page = 1;
    public SingleLiveEvent<String> isAD = new SingleLiveEvent<>();
    public SingleLiveEvent<String> shop_token = new SingleLiveEvent<>();

    public SingleLiveEvent<ExchangePointsRecordTabViewModel> deleteItemLiveData = new SingleLiveEvent<>();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
    }

    public ExchangePointsRecordViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<ExchangePointsRecordTabViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<ExchangePointsRecordTabViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_exchange_points_record_tab_item);

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestNetWork(false);
        }
    });

    public void onRefresh()
    {
        requestNetWork(false);
    }

    public void onLoadMore()
    {
        requestNetWork(true);
    }

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onLoadMore();
        }
    });

//    public void requestNetWork2(boolean isLoadMore) {
//        Log.e("TAG","==========requestNetWork=============");
//        if(!isLoadMore)
//        {
//            page = 1;
//        }
////        else
////        {
////            page++;
////        }
//
//        String coinID = "";
//        if(isAD.getValue())
//        {
//            coinID = ((AppApplication)AppApplication.getInstance()).getWalletCoins().get("AD");
//        }
//        else
//        {
//            coinID = ((AppApplication)AppApplication.getInstance()).getWalletCoins().get("积分");
//        }
//        model.exChangeLog(coinID,page+"")
//                .compose(RxUtils.schedulersTransformer()) //线程调度
//                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
//                .doOnSubscribe(this)//请求与ViewModel周期同步
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
////                        showDialog("正在请求...");
//                    }
//                })
//                .subscribe(new DisposableObserver<BaseResponse<List<ExchangeLogEntity>>>() {
//                    @Override
//                    public void onNext(BaseResponse<List<ExchangeLogEntity>> response) {
//                        Log.e("TAG","==========requestNetWork========onNext=====");
//                        if(!isLoadMore)
//                        {
//                            //清除列表
//                            observableList.clear();
//                        }
//                        if(response != null && response.getData() != null && response.getData().size() > 0)
//                        {
//                            for (ExchangeLogEntity entity : response.getData()) {
//                                ExchangePointsRecordTabViewModel itemViewModel = new ExchangePointsRecordTabViewModel(ExchangePointsRecordViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
//                            if(response != null && null != response.meta && null != response.meta.pagination)
//                            {
//                                page = response.meta.pagination.current_page;
//                                page++;
//                            }
//                        }
//                    }
//                    @Override
//                    public void onError(Throwable throwable) {
//                        Log.e("TAG","==========requestNetWork========onError====="+throwable.getMessage());
//                        //关闭对话框
////                        dismissDialog();
//                        if(!isLoadMore)
//                        {
//                            //请求刷新完成收回
//                            uc.finishRefreshing.call();
//                        }
//                        else
//                        {
//                            uc.finishLoadmore.call();
//                        }
////                        if (throwable instanceof ResponseThrowable) {
////                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
////                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        Log.e("TAG","==========requestNetWork========onComplete=====");
//                        //关闭对话框
////                        dismissDialog();
//                        if(!isLoadMore)
//                        {
//                            //请求刷新完成收回
//                            uc.finishRefreshing.call();
//                        }
//                        else
//                        {
//                            uc.finishLoadmore.call();
//                        }
//                    }
//                });
//    }
    public void requestNetWork(boolean isLoadMore) {
        Log.e("TAG","==========requestNetWork=============");
        if(!isLoadMore)
        {
            page = 1;
        }
//        else
//        {
//            page++;
//        }

        //暂时写死
        String coinID = "4";
        String coinID_duihuan = "7";
        Observable observable = null;
//        if(isAD.getValue().equals("AD"))
//        {
//            coinID = ((AppApplication)AppApplication.getInstance()).getWalletCoinsId("AD");
//            coinID_duihuan = ((AppApplication)AppApplication.getInstance()).getWalletCoinsId("CSC");
//
//            Log.e("TAG",coinID+"=========coinID=========otcBill=======coinID_duihuan====="+coinID_duihuan);
//            observable = model.otcBill(coinID,coinID_duihuan,page+"");
////            observable = model.exChangeLog("AD",page+"");
//        }
//        else if(isAD.getValue().equals("积分"))
//        {
//            coinID = ((AppApplication)AppApplication.getInstance()).getWalletCoinsId("积分");
//
//            String ad = ((AppApplication)AppApplication.getInstance()).getWalletCoinsId("AD");
//            String csc = ((AppApplication)AppApplication.getInstance()).getWalletCoinsId("CSC");
//            coinID_duihuan = ad + "," + csc;
//
//            observable = model.walletLog(page+"");
//        }

        observable = model.exChangeLog(coinID_duihuan,page+"");
//        model.otcBill("1",coinID,page+"")
        observable.compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe((Consumer<Disposable>) disposable -> showDialog("正在请求..."))
                .subscribe(new DisposableObserver<BaseResponse<List<ExchangeLogEntity>>>() {
                    @Override
                    public void onNext(BaseResponse<List<ExchangeLogEntity>> response) {
                        Log.e("TAG","==========requestNetWork=======onNext======");
                        if(!isLoadMore) {
                            //清除列表
                            observableList.clear();
                        }
                        if(response != null && response.getData() != null && response.getData().size() > 0)
                        {
                            for (ExchangeLogEntity entity : response.getData()) {
                                ExchangePointsRecordTabViewModel itemViewModel = new ExchangePointsRecordTabViewModel(ExchangePointsRecordViewModel.this, entity);
                                //双向绑定动态添加Item
                                observableList.add(itemViewModel);
                            }
//                            for (TransactionPlanListData.PlanList.PlanData entity : response.getData()) {
//                                TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
                            if(response != null && null != response.meta && null != response.meta.pagination)
                            {
                                page = response.meta.pagination.current_page;
                                page++;
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","==========requestNetWork=======onError======"+throwable.getMessage());
                        //关闭对话框
                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","==========requestNetWork=======onComplete======");
                        //关闭对话框
                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
                    }
                });
    }
    /**
     * 删除条目
     *
     * @param netWorkItemViewModel
     */
    public void deleteItem(ExchangePointsRecordTabViewModel netWorkItemViewModel) {
        //点击确定，在 observableList 绑定中删除，界面立即刷新
        observableList.remove(netWorkItemViewModel);
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(ExchangePointsRecordTabViewModel netWorkItemViewModel) {
        return observableList.indexOf(netWorkItemViewModel);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}